package com.symaster.common.swing.dialog.setting;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.symaster.common.swing.config.AppConfig;
import com.symaster.common.swing.dialog.setting.item.SettingItem;
import com.symaster.common.swing.element.button.SyzdButton;
import com.symaster.common.swing.element.list.SwingListAbs;
import com.symaster.common.swing.element.list.SwingListPanel;
import com.symaster.common.swing.style.Style;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.FontUIResource;
import javax.swing.text.StyleContext;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class SwingSettingsDialog extends JDialog {

    private final SwingListPanel swingListPanel;
    private JPanel contentPane;
    private JScrollPane root_scroll_panel;
    private JTextField title_text;
    private JPanel center_panel;
    private SyzdButton reset_button;
    private SyzdButton ok_button;
    private Map<String, SettingPageInterface> pagesMap;
    private SettingPageInterface thatSettingPage;

    public SwingSettingsDialog() {
        swingListPanel = new SwingListPanel(180, 40, new Color(30, 34, 38), 0, 5);
        $$$setupUI$$$();
        initPage();
    }

    public static void main(String[] args) {

        SwingSettingsDialog dialog = new SwingSettingsDialog();
        dialog.put(new SettingPageInterface() {

            private final JPanel jPanel = new JPanel();
            private final String uuid = UUID.randomUUID().toString();

            @Override
            public JComponent getRootPanel() {
                jPanel.setBackground(new Color(255, 0, 0));
                return jPanel;
            }

            @Override
            public String getTitle() {
                return "Hello";
            }

            @Override
            public String getUUID() {
                return uuid;
            }

            @Override
            public boolean saveProfileListener() {
                return false;
            }

            @Override
            public void reloadListener() {

            }
        });
        dialog.put(new SettingPageInterface() {

            private final JPanel jPanel = new JPanel();
            private final String uuid = UUID.randomUUID().toString();

            @Override
            public JComponent getRootPanel() {
                jPanel.setBackground(new Color(0, 255, 0));
                return jPanel;
            }

            @Override
            public String getTitle() {
                return "Hello";
            }

            @Override
            public String getUUID() {
                return uuid;
            }

            @Override
            public boolean saveProfileListener() {
                return false;
            }

            @Override
            public void reloadListener() {

            }
        });
        dialog.put(new SettingPageInterface() {

            private final JPanel jPanel = new JPanel();
            private final String uuid = UUID.randomUUID().toString();

            @Override
            public JComponent getRootPanel() {
                jPanel.setBackground(new Color(0, 0, 255));
                return jPanel;
            }

            @Override
            public String getTitle() {
                return "Hello";
            }

            @Override
            public String getUUID() {
                return uuid;
            }

            @Override
            public boolean saveProfileListener() {
                return false;
            }

            @Override
            public void reloadListener() {

            }
        });
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }

    private void initPage() {
        setTitle("Settings");
        int width = 900;
        int height = 600;
        setMinimumSize(new Dimension(600, 400));
        setPreferredSize(new Dimension(width, height));
        setContentPane(contentPane);
        setModal(true);

        initBorder();
        initListener();
        root_scroll_panel.setViewportView(swingListPanel);

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        ok_button.setForeground(AppConfig.getColor(AppConfig.SELECT_COLOR));

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        Point point = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        this.setBounds(point.x - width / 2, point.y - height / 2, width, height);
        this.pack();
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    private void initListener() {
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });
        swingListPanel.addSelectElementListener(this::onSelect);
        ok_button.addClickListener(() -> {
            if (thatSettingPage == null) {
                return;
            }
            thatSettingPage.saveProfileListener();
        });
        reset_button.addClickListener(() -> {
            if (thatSettingPage == null) {
                return;
            }
            thatSettingPage.reloadListener();
        });
    }

    private void onSelect(SwingListAbs select) {
        SettingItem item = (SettingItem) select;
        String uuid = item.getUuid();
        SettingPageInterface settingPageInterface = pagesMap.get(uuid);
        JComponent rootPanel = settingPageInterface.getRootPanel();
        rootPanel.setVisible(true);
        title_text.setText(settingPageInterface.getTitle());
        center_panel.removeAll();
        center_panel.add(rootPanel, BorderLayout.CENTER);
        center_panel.updateUI();
        this.thatSettingPage = settingPageInterface;
        settingPageInterface.reloadListener();
    }

    private void initBorder() {
        Style.setBorder(Style.BORDER_EMPTY, title_text);
    }

    private void loadPageList() {
        if (this.pagesMap == null) {
            return;
        }
        this.pagesMap.forEach((k, v) -> {
            swingListPanel.put(new SettingItem(v.getUUID(), v.getTitle()));
        });
    }

    public void put(SettingPageInterface page) {
        if (this.pagesMap == null) {
            this.pagesMap = new HashMap<>();
        }
        if (page == null || StringUtils.isEmpty(page.getUUID())) {
            throw new IllegalArgumentException("page == null || StringUtils.isEmpty(page.getUUID())");
        }
        if (this.pagesMap.get(page.getUUID()) != null) {
            throw new IllegalArgumentException("id不唯一");
        }

        this.pagesMap.put(page.getUUID(), page);
        SettingItem item = new SettingItem(page.getUUID(), page.getTitle());
        this.swingListPanel.put(item);
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        createUIComponents();
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(0, 0));
        contentPane.setBackground(new Color(-14276050));
        contentPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new BorderLayout(0, 0));
        panel1.setBackground(new Color(-14802394));
        panel1.setPreferredSize(new Dimension(180, -1));
        contentPane.add(panel1, BorderLayout.WEST);
        panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        root_scroll_panel = new JScrollPane();
        panel1.add(root_scroll_panel, BorderLayout.CENTER);
        root_scroll_panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new BorderLayout(0, 0));
        panel2.setBackground(new Color(-14276050));
        contentPane.add(panel2, BorderLayout.CENTER);
        panel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new GridLayoutManager(1, 1, new Insets(0, 25, 0, 0), -1, -1));
        panel3.setBackground(new Color(-14276050));
        panel3.setPreferredSize(new Dimension(24, 50));
        panel3.setVisible(true);
        panel2.add(panel3, BorderLayout.NORTH);
        panel3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        title_text = new JTextField();
        title_text.setBackground(new Color(-14276050));
        title_text.setDisabledTextColor(new Color(-525313));
        title_text.setEditable(false);
        title_text.setEnabled(false);
        Font title_textFont = this.$$$getFont$$$("Segoe UI", -1, 18, title_text.getFont());
        if (title_textFont != null) title_text.setFont(title_textFont);
        title_text.setText("欢迎");
        panel3.add(title_text, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        center_panel = new JPanel();
        center_panel.setLayout(new BorderLayout(0, 0));
        center_panel.setBackground(new Color(-14276050));
        panel2.add(center_panel, BorderLayout.CENTER);
        center_panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel4 = new JPanel();
        panel4.setLayout(new GridLayoutManager(1, 1, new Insets(5, 15, 5, 15), -1, -1));
        panel4.setBackground(new Color(-14276050));
        panel4.setPreferredSize(new Dimension(0, 35));
        panel2.add(panel4, BorderLayout.SOUTH);
        panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        final JPanel panel5 = new JPanel();
        panel5.setLayout(new BorderLayout(0, 0));
        panel5.setBackground(new Color(-14276050));
        panel4.add(panel5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(150, -1), new Dimension(150, -1), new Dimension(150, -1), 0, false));
        panel5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        reset_button = new SyzdButton();
        reset_button.setPreferredSize(new Dimension(70, 28));
        reset_button.setText("Reset");
        panel5.add(reset_button, BorderLayout.WEST);
        ok_button.setPreferredSize(new Dimension(70, 28));
        ok_button.setText("Save");
        panel5.add(ok_button, BorderLayout.EAST);
    }

    /**
     * @noinspection ALL
     */
    private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
        if (currentFont == null) return null;
        String resultName;
        if (fontName == null) {
            resultName = currentFont.getName();
        } else {
            Font testFont = new Font(fontName, Font.PLAIN, 10);
            if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
                resultName = fontName;
            } else {
                resultName = currentFont.getName();
            }
        }
        Font font = new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
        boolean isMac = System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).startsWith("mac");
        Font fontWithFallback = isMac ? new Font(font.getFamily(), font.getStyle(), font.getSize()) : new StyleContext().getFont(font.getFamily(), font.getStyle(), font.getSize());
        return fontWithFallback instanceof FontUIResource ? fontWithFallback : new FontUIResource(fontWithFallback);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }
}
